/**
 *
 */
package org.shan.security.core.social.ali.api;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

/**
 * @author zhailiang
 *
 */
public class AliImpl extends AbstractOAuth2ApiBinding implements Ali {

	private Logger logger = LoggerFactory.getLogger(AliImpl.class);

	// 根据access_token获取openID
	private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

	// 根据openID获取用户信息
	private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

	private String appId;

	private String openId;

	private ObjectMapper objectMapper = new ObjectMapper();

	public AliImpl(String accessToken, String appId) {

		// 默认是把accessToken放入请求头中
		// qqapi的文档确是放在参数中传递的
		super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);

		this.appId = appId;

		String url = String.format(URL_GET_OPENID, accessToken);
		String result = getRestTemplate().getForObject(url, String.class);

		logger.info(result);

		this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
	}

	/* (non-Javadoc)
	 * @see com.imooc.security.core.social.qq.api.Ali#getUserInfo()
	 */
	@Override
	public AliUserInfo getUserInfo() {

		String url = String.format(URL_GET_USERINFO, appId, openId);
		String result = getRestTemplate().getForObject(url, String.class);

		logger.info(result);

		AliUserInfo userInfo = null;
		try {
			userInfo = objectMapper.readValue(result, AliUserInfo.class);
			userInfo.setOpenId(openId);
			return userInfo;
		} catch (Exception e) {
			throw new RuntimeException("获取用户信息失败", e);
		}
	}

}
